package com.winning.rabbitmq.simple;

import com.rabbitmq.client.*;
import com.winning.rabbitmq.ConnectionUtils;
import com.winning.utils.IOUtils;

import java.io.IOException;

public class MyConsumer {

    private final static String EXCHANGE_NAME = "SIMPLE_EXCHANGE";
    private final static String QUEUE_NAME = "SIMPLE_QUEUE";

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;

        try{
            connection = ConnectionUtils.getConnection();
            //创建消息通道
            channel = connection.createChannel();

            //声明交换机
            channel.exchangeDeclare(EXCHANGE_NAME, "direct",false, false, null);
            channel.queueDeclare(QUEUE_NAME,false, false, false, null);
            //绑定队列和交换机
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "gupao.best");
            System.out.println(" Waiting for message....");
            //创建消费者
            Consumer consumer = new DefaultConsumer(channel){

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body, "UTF-8");
                    System.out.println("Received message : '" + msg + "'");
                    System.out.println("consumerTag : " + consumerTag );
                    System.out.println("deliveryTag : " + envelope.getDeliveryTag() );
                }
            };

            //开始消费
            channel.basicConsume(QUEUE_NAME, true, consumer);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
//            IOUtils.close(channel);
//            IOUtils.close(connection);
        }
    }

}
